<template>
  <div class="padd30px">
    <a-card title="系统菜单">
      <div style="margin-bottom: 16px;">
        <a-button type="primary" @click="openAddModal({ key: null, parentId: 0 })">新增一级菜单</a-button>

        <a-button :disabled="checkedKeys.length==0" style="margin-left: 30px;" @click="deleteNode">删除</a-button>
      </div>

      <div v-if="treeData.length">
        <a-tree
          v-model:expandedKeys="expandedKeys"
          v-model:selectedKeys="selectedKeys"
          v-model:checkedKeys="checkedKeys"
          checkable
          :tree-data="treeData"
        >
          <!-- 自定义标题模板 -->
          <template #title="{ title, key }">
            <span>{{ title }}</span>
            <a-button style="margin-left: 30px" @click.stop="openEditModal({ title, key })">编辑</a-button>
            <a-button style="margin-left: 10px" @click.stop="openAddModal({ title, key })">新增子菜单</a-button>
          </template>
        </a-tree>
      </div>
      <div v-else>加载中...</div>
    </a-card>

    <!-- 编辑弹窗 -->
    <a-modal v-model:open="editModalVisible" title="编辑菜单项" @ok="handleEditOk">
      <a-form :model="currentEditNode" layout="vertical">
        <a-form-item label="标题 (nickName)">
          <a-input v-model:value="currentEditNode.nickName" />
        </a-form-item>
        <a-form-item label="路由路径 (path)">
          <a-input v-model:value="currentEditNode.path" />
        </a-form-item>
        <a-form-item label="国际化标识 (menuName)">
          <a-input v-model:value="currentEditNode.menuName" />
        </a-form-item>
        <!-- <a-form-item label="图标 (icon)">
          <a-input v-model:value="currentEditNode.icon" />
        </a-form-item> -->
        <a-form-item label="父级 ID (parentId)">
          <a-input v-model:value="currentEditNode.parentId" disabled />
        </a-form-item>
        <a-form-item label="Key">
          <a-input v-model:value="currentEditNode.key" disabled />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 新增弹窗 -->
    <a-modal v-model:open="addModalVisible" title="新增菜单项" @ok="handleAddOk">
      <a-form :model="newMenuForm" layout="vertical">
        <a-form-item label="标题 (nickName)">
          <a-input v-model:value="newMenuForm.nickName" placeholder="请输入标题" />
        </a-form-item>
        <a-form-item label="路由路径 (path)">
          <a-input v-model:value="newMenuForm.path" placeholder="请输入路由路径" />
        </a-form-item>
        <a-form-item label="国际化标识 (menuName)">
          <a-input v-model:value="newMenuForm.menuName" placeholder="请输入国际化标识" />
        </a-form-item>
        <!-- <a-form-item label="图标 (icon)">
          <a-input v-model:value="newMenuForm.icon" placeholder="请输入图标类名" />
        </a-form-item> -->
        <a-form-item label="父级 ID (parentId)">
          <a-input  v-model:value="newMenuForm.parentId" disabled />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import type { TreeProps } from 'ant-design-vue';
import { getAccessMenusApi, routerUpdateApi,routerSaveApi,routerDeleteApi } from '#/api/object/router';

// 菜单数据
const treeData = ref<TreeProps[]>([]);
const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);
const checkedKeys = ref<string[]>([]);

const deleteNode=()=>{
  //  console.log("checkedKeys",checkedKeys.value)
   routerDeleteApi(checkedKeys.value).then(res=>{
      getList()
   })
}

// 编辑相关
const editModalVisible = ref(false);
const currentEditNode = ref({
  nickName: '',
  path: '',
  menuName: '',
  icon: '',
  parentId: 0,
  key: '',
});

// 新增相关
const addModalVisible = ref(false);
const newMenuForm = ref({
  nickName: '',
  path: '',
  menuName: '',
  icon: '',
  parentId: 0,
});
let currentNodeKeyForAdd = ref<string | null>(null); // 可能为 null 表示新增一级菜单

// 将后端数据转为 a-tree 需要的格式
const convertToTreeData = (menus: any[]): TreeProps[] => {
  return menus.map(menu => ({
    ...menu,
    title: menu.nickName,
    key: String(menu.id),
    children: menu.children ? convertToTreeData(menu.children) : undefined,
  }));
};

// 辅助函数：提取所有 key 用于默认展开
const getAllKeys = (data: TreeProps[]): string[] => {
  let keys: string[] = [];
  data.forEach(item => {
    keys.push(item?.key as string);
    if (item.children) {
      keys = keys.concat(getAllKeys(item.children));
    }
  });
  return keys;
};

// 获取菜单数据并转换
const getList = async () => {
  try {
    const res = await getAccessMenusApi();
    // console.log('【接口返回】', res);

    const menus = res.data || [];
    // console.log('【转换前数据】', menus);

    const transformed = convertToTreeData(menus);
    // console.log('【转换后数据】', transformed);

    treeData.value = transformed;

    if (transformed.length > 0) {
      expandedKeys.value = getAllKeys(transformed);
    }
  } catch (error) {
    console.error('【获取菜单失败】', error);
  }
};

// 打开编辑弹窗
const openEditModal = (node) => {
  const foundNode = findNodeByKey(treeData.value, node.key);
  if (foundNode) {
    currentEditNode.value = { ...foundNode };
    editModalVisible.value = true;
  }
};

// 提交编辑
const handleEditOk = () => {
  const updateNode = (nodes) => {
    return nodes.map(node => {
      if (node.key === currentEditNode.value.key) {
        return {
          ...node,
          title: currentEditNode.value.nickName,
          path: currentEditNode.value.path,
          menuName: currentEditNode.value.menuName,
          icon: currentEditNode.value.icon,
        };
      }
      if (node.children) {
        return { ...node, children: updateNode(node.children) };
      }
      return node;
    });
  };

  treeData.value = updateNode(treeData.value);
  console.log("currentEditNode.value",currentEditNode.value)
     routerUpdateApi(formatToBackend(currentEditNode.value)).then(res=>{
       getList()
    })

  editModalVisible.value = false;
};

// 转换为后端需要的格式
const formatToBackend = (node) => {
  return {
    id: node.key ? parseInt(node.key) : undefined, // key -> id (int)
    path: node.path,
    parentId: node.parentId,
    menuName: node.menuName,
    icon: node.icon,
    nickName:node.nickName
  };
};

// 打开新增弹窗
const openAddModal = (node) => {
  currentNodeKeyForAdd.value = node.key;
  newMenuForm.value = {
    nickName: '',
    path: '',
    menuName: '',
    icon: '',
    parentId: node.parentId ?? node.key ? parseInt(node.key) : 0,
  };
  addModalVisible.value = true;
};

// 提交新增
const handleAddOk = () => {
  // const newKey = Date.now().toString(); // 模拟唯一 key
  const newNode = {
    title: newMenuForm.value.nickName,
    nickName: newMenuForm.value.nickName,
    // key: newKey,
    path: newMenuForm.value.path,
    menuName: newMenuForm.value.menuName,
    icon: newMenuForm.value.icon,
    parentId: newMenuForm.value.parentId,
    children: [],
  };

  const addChildNode = (nodes) => {
    return nodes.map(node => {
      if (node.key === currentNodeKeyForAdd.value) {
        const children = node.children || [];
        return {
          ...node,
          children: [...children, newNode],
        };
      }
      if (node.children) {
        return {
          ...node,
          children: addChildNode(node.children),
        };
      }
      return node;
    });
  };

  if (!currentNodeKeyForAdd.value) {
    // 新增一级菜单
    treeData.value = [...treeData.value, newNode];
  } else {
    // 新增子菜单
    treeData.value = addChildNode(treeData.value);
    expandedKeys.value = [...expandedKeys.value, currentNodeKeyForAdd.value];
  }
    routerSaveApi(formatToBackend(newNode)).then(res=>{
       getList()
    })

  addModalVisible.value = false;
};

// 根据 key 找到节点
const findNodeByKey = (nodes, targetKey): any => {
  for (const node of nodes) {
    if (node.key === targetKey) {
      return node;
    }
    if (node.children) {
      const found = findNodeByKey(node.children, targetKey);
      if (found) return found;
    }
  }
  return null;
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.padd30px {
  padding: 30px;
}
</style>
